package org.riahispano.twitterds.services.impl;

import org.apache.log4j.Logger;
import org.riahispano.twitterds.exception.TwitterDSException;
import org.riahispano.twitterds.services.TwitterSendMessageService;
import org.springframework.flex.remoting.RemotingDestination;
import org.springframework.flex.remoting.RemotingInclude;
import org.springframework.stereotype.Service;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;


/**
 * @author: ecamacho
 * riahispano 2010
 */
@Service("twitterSendMessageService")
@RemotingDestination( channels={"my-amf"})
public class TwitterSendMessageServiceImpl implements TwitterSendMessageService {

    private static final Logger logger = Logger.getLogger( TwitterSendMessageServiceImpl.class.getName() );

        /* (non-Javadoc)
         * @see org.riahispano.twitterds.services.TwitterSendMessageService#sendMessage(java.lang.String, java.lang.String, java.lang.String)
         */
        @RemotingInclude
        public long sendMessage(String user, String password, String message) {
            if( !isMessageValid( message ) )
            {
                throw new TwitterDSException( "[Invalid twitter message] " + message );
            }
            Twitter twitter = new Twitter( user, password );
            long id;
            try {
                Status status = twitter.updateStatus( message );
                id 			  = status.getId();
            } catch (TwitterException e) {
                logger.error( "[Error sending message] " + message, e);
                throw new TwitterDSException( "[Error sending message] " + message, e );
            }
            return id;
        }

        private boolean isMessageValid( String message )
        {
            boolean valid = true;
            valid = message != null? message.trim().length() <= 140: false;

            return valid;
        }

}
